<template>
  <view class="container">
    <!-- 顶部安全区域占位，使用动态高度 -->
    <view class="status-bar-height" :style="{height: statusBarHeight + 120 + 'rpx'}"></view>
    
    <view class="header">
      <view class="search-box">
        <image src="/static/搜索.png" class="search-icon"></image>
        <input 
          type="text" 
          placeholder="搜索景点/美食/攻略" 
          confirm-type="search" 
          focus
          v-model="searchText" 
          @confirm="search"
          @input="search"
        />
        <text class="cancel-btn" @tap="goBack">取消</text>
      </view>
    </view>
    
    <!-- 搜索tab -->
    <view class="search-tabs" v-if="searched">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{'active': currentTab === index}"
        @tap="switchTab(index)"
      >
        <text class="tab-text">{{tab.name}}</text>
        <text class="tab-count" v-if="tab.count > 0">({{tab.count}})</text>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="results-container" v-if="searched">
      <swiper class="results-swiper" :current="currentTab" @change="handleTabChange">
        <!-- 全部结果 -->
        <swiper-item>
          <scroll-view scroll-y class="results-scroll">
            <!-- 景点结果 -->
            <view class="section" v-if="attractionsResults.length > 0">
              <view class="section-header">
                <text class="section-title">景点</text>
                <text class="more-text" @tap="switchTab(1)">更多 ></text>
              </view>
              <view class="result-list">
                <view class="attraction-item" v-for="item in attractionsResults.slice(0, 2)" :key="item.id" @tap="navigateToDetail('attraction', item.id)">
                  <image class="item-image" :src="item.coverImage" mode="aspectFill"></image>
                  <view class="item-info">
                    <text class="item-name">{{item.name}}</text>
                    <view class="tags-row">
                      <text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
                    </view>
                    <view class="rating-row">
                      <text class="rating">{{item.rating}}分</text>
                      <text class="count">{{item.visitCount}}人去过</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 美食结果 -->
            <view class="section" v-if="foodsResults.length > 0">
              <view class="section-header">
                <text class="section-title">美食</text>
                <text class="more-text" @tap="switchTab(2)">更多 ></text>
              </view>
              <view class="result-list">
                <view class="food-item" v-for="item in foodsResults.slice(0, 2)" :key="item.id" @tap="navigateToDetail('food', item.id)">
                  <image class="item-image" :src="item.coverImage" mode="aspectFill"></image>
                  <view class="item-info">
                    <text class="item-name">{{item.name}}</text>
                    <view class="tags-row">
                      <text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
                    </view>
                    <view class="rating-row">
                      <text class="rating">{{item.rating}}分</text>
                      <text class="price">¥{{item.avgPrice}}/人</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 攻略结果 -->
            <view class="section" v-if="guidesResults.length > 0">
              <view class="section-header">
                <text class="section-title">攻略</text>
                <text class="more-text" @tap="switchTab(3)">更多 ></text>
              </view>
              <view class="result-list">
                <view class="guide-item" v-for="item in guidesResults.slice(0, 2)" :key="item.id" @tap="navigateToDetail('guide', item.id)">
                  <image class="item-image" :src="item.coverImage || item.cover" mode="aspectFill"></image>
                  <view class="item-info">
                    <text class="item-name">{{item.title}}</text>
                    <view class="author-row">
                      <image class="author-avatar-small" :src="item.authorAvatar" mode="aspectFill"></image>
                      <text class="author-name-small">{{item.authorName}}</text>
                    </view>
                    <view class="rating-row">
                      <text class="like-count-small">{{item.likeCount}}人喜欢</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="placeholder"></view>
          </scroll-view>
        </swiper-item>
        
        <!-- 景点结果 -->
        <swiper-item>
          <scroll-view scroll-y class="results-scroll">
            <view class="empty-state" v-if="attractionsResults.length === 0">
              <text class="empty-text">未找到相关景点</text>
            </view>
            <view class="result-list full-list" v-else>
              <view class="attraction-item" v-for="(item, index) in attractionsResults" :key="item.id" @tap="navigateToDetail('attraction', item.id)">
                <image class="item-image" :src="item.coverImage" mode="aspectFill"></image>
                <view class="item-info">
                  <text class="item-name">{{item.name}}</text>
                  <view class="tags-row">
                    <text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
                  </view>
                  <view class="rating-row">
                    <text class="rating">{{item.rating}}分</text>
                    <text class="count">{{item.visitCount}}人去过</text>
                  </view>
                </view>
              </view>
            </view>
            <view class="placeholder"></view>
          </scroll-view>
        </swiper-item>
        
        <!-- 美食结果 -->
        <swiper-item>
          <scroll-view scroll-y class="results-scroll">
            <view class="empty-state" v-if="foodsResults.length === 0">
              <text class="empty-text">未找到相关美食</text>
            </view>
            <view class="result-list full-list" v-else>
              <view class="food-item" v-for="(item, index) in foodsResults" :key="item.id" @tap="navigateToDetail('food', item.id)">
                <image class="item-image" :src="item.coverImage" mode="aspectFill"></image>
                <view class="item-info">
                  <text class="item-name">{{item.name}}</text>
                  <view class="tags-row">
                    <text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
                  </view>
                  <view class="rating-row">
                    <text class="rating">{{item.rating}}分</text>
                    <text class="price">¥{{item.avgPrice}}/人</text>
                  </view>
                </view>
              </view>
            </view>
            <view class="placeholder"></view>
          </scroll-view>
        </swiper-item>
        
        <!-- 攻略结果 -->
        <swiper-item>
          <scroll-view scroll-y class="results-scroll">
            <view class="empty-state" v-if="guidesResults.length === 0">
              <text class="empty-text">未找到相关攻略</text>
            </view>
            <view class="result-list full-list" v-else>
              <view class="guide-item" v-for="(item, index) in guidesResults" :key="item.id" @tap="navigateToDetail('guide', item.id)">
                <image class="item-image" :src="item.coverImage || item.cover" mode="aspectFill"></image>
                <view class="item-info">
                  <text class="item-name">{{item.title}}</text>
                  <view class="author-row">
                    <image class="author-avatar-small" :src="item.authorAvatar" mode="aspectFill"></image>
                    <text class="author-name-small">{{item.authorName}}</text>
                  </view>
                  <view class="rating-row">
                    <text class="like-count-small">{{item.likeCount}}人喜欢</text>
                  </view>
                </view>
              </view>
            </view>
            <view class="placeholder"></view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-state" v-if="isLoading">
      <text class="loading-text">正在搜索...</text>
    </view>
    
    <!-- 热门搜索 -->
    <view class="search-content" v-if="!searchText && !searched">
      <view class="hot-searches">
        <text class="section-title">热门搜索</text>
        <view class="keywords">
          <text 
            class="keyword-item" 
            v-for="(item, index) in hotKeywords" 
            :key="index"
            @tap="quickSearch(item)"
          >{{item}}</text>
        </view>
      </view>
      
      <view class="hot-searches">
        <text class="section-title">搜索历史</text>
        <view class="keywords history-keywords" v-if="searchHistory.length > 0">
          <text 
            class="keyword-item history-item" 
            v-for="(item, index) in searchHistory" 
            :key="index"
            @tap="quickSearch(item)"
          >{{item}}</text>
        </view>
        <view class="empty-history" v-else>
          <text class="empty-text">暂无搜索历史</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入模糊搜索工具
import searchUtils from '../../utils/search.js';

// 静态攻略数据
const staticGuides = [
  {
    id: 1,
    title: '🔥玩沙扒湾(三天行)——很全攻略',
    cover: '/static/图片.jpg',
    coverImage: '/static/图片.jpg',
    authorName: 'sanseafish晓',
    authorAvatar: '/static/logo.png',
    likeCount: 33,
    type: '全部攻略',
    content: '沙扒湾是广东省阳江市阳西县南部一个小渔村，到处是静谧的渔港，是摄影爱好者的天堂。这里山清水秀，空气清新，幽静美丽，气候宜人，四季如春，是度假、疗养和旅游的绝佳去处。'
  },
  {
    id: 2,
    title: '值得收藏！沙扒湾最好吃美食TOP5——这是完美攻略',
    cover: '/static/图片.jpg',
    coverImage: '/static/图片.jpg',
    authorName: 'sanseafish晓',
    authorAvatar: '/static/logo.png',
    likeCount: 55,
    type: '美食',
    content: '沙扒湾的海鲜非常新鲜，强烈推荐阿强海鲜大排档，这里的螃蟹和生蚝特别新鲜，价格也不贵。另外，沙扒湾的烧烤也非常有特色，海岸线烧烤屋的烤生蚝、烤鱿鱼都是必点美食。'
  },
  {
    id: 3,
    title: '如果你半夜去沙扒湾的——定会吃到好吃',
    cover: '/static/图片.jpg',
    coverImage: '/static/图片.jpg',
    authorName: '旅游家沙爸的心',
    authorAvatar: '/static/logo.png',
    likeCount: 45,
    type: '美食',
    content: '夜晚的沙扒湾别有一番风味，特别是沙滩BBQ炭烤，在海边吹着海风，听着浪声，吃着美味的烧烤，喝着啤酒，绝对是人生一大享受。'
  },
  {
    id: 4,
    title: '可以去这些沙滩玩耍!',
    cover: '/static/图片.jpg',
    coverImage: '/static/图片.jpg',
    authorName: 'sanseafish晓',
    authorAvatar: '/static/logo.png',
    likeCount: 55,
    type: '沙滩',
    content: '沙扒湾有很多美丽的沙滩，非常适合放松和玩耍。沙扒湾沙滩细软洁白，海水湛蓝清澈，是游泳、冲浪、玩水的好地方。黄昏时分还可以欣赏到美丽的日落景色。'
  },
  {
    id: 5,
    title: '值得收藏！沙扒湾最好吃美食TOP5——这是完美攻略',
    cover: '/static/图片.jpg',
    coverImage: '/static/图片.jpg',
    authorName: 'sanseafish晓',
    authorAvatar: '/static/logo.png',
    likeCount: 55,
    type: '出片景点',
    content: '沙扒湾有许多适合拍照的景点，如海陵岛、沙扒湾海滩等。尤其是黄昏时分的沙扒湾海滩，落日余晖洒在金色的沙滩上，是拍摄绝美照片的好时机。'
  }
];

// 静态景点数据
const staticAttractions = [
  {
    id: '1',
    name: '沙扒湾海滩',
    coverImage: '/static/图片.jpg',
    tags: ['海滩', '日落', '游泳'],
    rating: 4.8,
    visitCount: 5280,
    category: 'attraction',
    type: 'beach' // 类型为海滩
  },
  {
    id: '2',
    name: '闸坡海陵岛',
    coverImage: '/static/图片.jpg',
    tags: ['岛屿', '海鲜', '度假'],
    rating: 4.6,
    visitCount: 8320,
    category: 'attraction',
    type: 'beach' // 类型为海滩
  },
  {
    id: '3',
    name: '沙扒湾游乐园',
    coverImage: '/static/图片.jpg',
    tags: ['游乐', '亲子', '刺激'],
    rating: 4.5,
    visitCount: 3120,
    category: 'attraction',
    type: 'entertainment' // 类型为娱乐设施
  },
  {
    id: '4',
    name: '海上水上乐园',
    coverImage: '/static/图片.jpg',
    tags: ['水上', '娱乐', '清凉'],
    rating: 4.4,
    visitCount: 2870,
    category: 'attraction',
    type: 'entertainment' // 类型为娱乐设施
  },
  {
    id: '5',
    name: '阳江海洋博物馆',
    coverImage: '/static/图片.jpg',
    tags: ['博物馆', '科普', '历史'],
    rating: 4.3,
    visitCount: 1920,
    category: 'attraction',
    type: 'museum' // 类型为博物馆
  }
];

// 静态美食数据
const staticFoods = [
  {
    id: '1',
    name: '阿强海鲜大排档',
    coverImage: '/static/图片.jpg',
    tags: ['海鲜', '排档', '螃蟹'],
    rating: 4.8,
    avgPrice: 128,
    address: '沙扒湾海滨路58号',
    category: 'food',
    type: 'seafood' // 类型为海鲜
  },
  {
    id: '2',
    name: '海岸线烧烤屋',
    coverImage: '/static/图片.jpg',
    tags: ['烧烤', '啤酒', '海鲜'],
    rating: 4.7,
    avgPrice: 98,
    address: '沙扒湾沙滩路12号',
    category: 'food',
    type: 'bbq' // 类型为烧烤
  },
  {
    id: '3',
    name: '沙扒湾渔村小馆',
    coverImage: '/static/图片.jpg',
    tags: ['家常菜', '农家菜', '特色'],
    rating: 4.6,
    avgPrice: 88,
    address: '沙扒湾渔村路33号',
    category: 'food',
    type: 'local' // 类型为本地特色
  },
  {
    id: '4',
    name: '火辣辣重庆火锅',
    coverImage: '/static/图片.jpg',
    tags: ['火锅', '麻辣', '牛肉'],
    rating: 4.5,
    avgPrice: 108,
    address: '沙扒湾商业街45号',
    category: 'food',
    type: 'hotpot' // 类型为火锅
  },
  {
    id: '5',
    name: '海上明月海鲜酒楼',
    coverImage: '/static/图片.jpg',
    tags: ['粤菜', '海鲜', '包厢'],
    rating: 4.4,
    avgPrice: 168,
    address: '沙扒湾滨海大道88号',
    category: 'food',
    type: 'seafood' // 类型为海鲜
  }
];

export default {
  data() {
    return {
      searchText: '',
      isLoading: false,
      searched: false,
      currentTab: 0,
      tabs: [
        { name: '全部', count: 0 },
        { name: '景点', count: 0 },
        { name: '美食', count: 0 },
        { name: '攻略', count: 0 }
      ],
      attractionsResults: [],
      foodsResults: [],
      guidesResults: [],
      hotKeywords: ['沙扒湾', '海鲜', '沙滩', '日落', '美食'],
      searchHistory: [],
      statusBarHeight: 20 // 默认状态栏高度
    }
  },
  onLoad() {
    // 从本地存储获取搜索历史
    try {
      const history = uni.getStorageSync('searchHistory');
      if (history) {
        this.searchHistory = JSON.parse(history);
      }
    } catch (e) {
      console.error('获取搜索历史失败:', e);
    }
    
    // 获取系统信息设置状态栏高度
    uni.getSystemInfo({
      success: (res) => {
        this.statusBarHeight = res.statusBarHeight;
        console.log('状态栏高度:', this.statusBarHeight);
      }
    });
  },
  methods: {
    // 全局搜索
    search() {
      if (!this.searchText.trim()) {
        this.clearResults();
        return;
      }
      
      this.isLoading = true;
      this.searched = true;
      
      // 为了模拟真实的搜索效果，这里使用setTimeout
      setTimeout(() => {
        // 搜索景点
        this.attractionsResults = searchUtils.fuzzySearch(
          staticAttractions,
          this.searchText,
          ['name', 'tags']
        );
        
        // 搜索美食
        this.foodsResults = searchUtils.fuzzySearch(
          staticFoods,
          this.searchText,
          ['name', 'tags', 'address']
        );
        
        // 搜索攻略
        this.guidesResults = searchUtils.fuzzySearch(
          staticGuides,
          this.searchText,
          ['title', 'content', 'type', 'authorName']
        );
        
        // 更新tab计数
        this.tabs[0].count = this.attractionsResults.length + this.foodsResults.length + this.guidesResults.length;
        this.tabs[1].count = this.attractionsResults.length;
        this.tabs[2].count = this.foodsResults.length;
        this.tabs[3].count = this.guidesResults.length;
        
        this.isLoading = false;
        
        // 保存搜索历史
        if (this.searchText.trim() && this.tabs[0].count > 0) {
          this.saveSearchHistory(this.searchText);
        }
      }, 300);
    },
    
    // 清除搜索结果
    clearResults() {
      this.attractionsResults = [];
      this.foodsResults = [];
      this.guidesResults = [];
      this.searched = false;
      this.tabs.forEach(tab => { tab.count = 0; });
    },
    
    // 快速搜索
    quickSearch(keyword) {
      this.searchText = keyword;
      this.search();
    },
    
    // 切换tab
    switchTab(index) {
      this.currentTab = index;
    },
    
    // 处理tab切换事件
    handleTabChange(e) {
      this.currentTab = e.detail.current;
    },
    
    // 跳转到详情页
    navigateToDetail(type, id) {
      let url = '';
      
      switch(type) {
        case 'attraction':
          url = `/pages/attractions/detail?id=${id}`;
          break;
        case 'food':
          url = `/pages/foods/detail?id=${id}`;
          break;
        case 'guide':
          url = `/pages/guide/detail?id=${id}`;
          break;
      }
      
      if (url) {
        uni.navigateTo({ url });
      }
    },
    
    // 保存搜索历史
    saveSearchHistory(keyword) {
      // 如果已存在，先删除旧的
      const index = this.searchHistory.indexOf(keyword);
      if (index > -1) {
        this.searchHistory.splice(index, 1);
      }
      
      // 添加到历史开头
      this.searchHistory.unshift(keyword);
      
      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10);
      }
      
      // 保存到本地存储
      try {
        uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory));
      } catch (e) {
        console.error('保存搜索历史失败:', e);
      }
    },
    
    // 返回
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style>
/* 状态栏高度 - 这里将不设置固定高度，改为在模板中动态设置 */
.status-bar-height {
  width: 100%;
  background-color: #fff;
}

.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30rpx;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.header {
  background-color: #fff;
  padding: 30rpx 30rpx 20rpx; /* 增加顶部内边距，减少底部内边距，总高度保持平衡 */
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
}

.search-box {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
}

.search-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 15rpx;
}

.search-box input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 30rpx;
}

.cancel-btn {
  font-size: 28rpx;
  color: #333;
  margin-left: 20rpx;
  padding: 10rpx;
}

/* 搜索tab */
.search-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  padding: 0 20rpx;
  margin-top: 10rpx;
}

.tab-item {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #ff5a5f;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #ff5a5f;
}

.tab-count {
  font-size: 24rpx;
  color: #999;
  margin-left: 6rpx;
}

/* 搜索结果 */
.results-container {
  flex: 1;
  height: calc(100vh - 170rpx);
  margin-top: 10rpx;
}

.results-swiper {
  height: 100%;
}

.results-scroll {
  height: 100%;
}

.section {
  background-color: #fff;
  margin: 20rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  margin-top: 10rpx;
  display: block;
}

.more-text {
  font-size: 24rpx;
  color: #999;
}

.result-list {
  display: flex;
  flex-direction: column;
}

.full-list {
  margin: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.attraction-item, .food-item, .guide-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 15rpx;
}

.attraction-item:last-child, 
.food-item:last-child, 
.guide-item:last-child {
  margin-bottom: 5rpx;
  border-bottom: none;
}

.item-image {
  width: 180rpx;
  height: 140rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.tags-row, .author-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 10rpx;
}

.tag {
  font-size: 22rpx;
  color: #ff5a5f;
  background-color: rgba(255, 90, 95, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
  margin-bottom: 6rpx;
}

.author-avatar {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  margin-right: 10rpx;
}

.author-name {
  font-size: 24rpx;
  color: #666;
}

.rating-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rating, .count, .price, .like-count {
  font-size: 24rpx;
  color: #999;
}

.rating {
  color: #ff9650;
}

/* 占位元素 */
.placeholder {
  height: 30rpx;
}

/* 热门搜索 */
.search-content {
  padding: 20rpx;
  margin-top: 40rpx; /* 增加顶部间距 */
}

.hot-searches {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx; /* 增加内部填充 */
  margin-bottom: 30rpx; /* 增加底部间距 */
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.keywords {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.keyword-item {
  font-size: 26rpx;
  color: #666;
  background-color: #f8f8f8;
  padding: 15rpx 30rpx;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.history-item {
  color: #999;
  background-color: #f0f0f0;
}

.empty-history {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
  margin-top: 10rpx;
}

.empty-state, .loading-state {
  padding: 60rpx 0;
  text-align: center;
}

.empty-text, .loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 添加小尺寸样式，用于攻略条目显示 */
.author-avatar-small {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  margin-right: 10rpx;
}

.author-name-small {
  font-size: 24rpx;
  color: #666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.like-count-small {
  font-size: 24rpx;
  color: #999;
}
</style> 